<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button index="1">btn1</button>
    <button index="2">btn2</button>
    <button index="3">btn3</button>

    <script>
      const btnsEl = document.querySelectorAll("button");

      // 闭包
      /*for (var i = 0; i < btnsEl.length; i++) {
        btnsEl[i].onclick = function () {
          console.log(`当前索引${i}`);
        };
      }

      for (var i = 0; i < btnsEl.length; i++) {
        (function (i) {
          btnsEl[i].onclick = function () {
            console.log(`当前索引${i}`);
          };
        })(i);
      }

      for (var i = 0; i < btnsEl.length; i++) {
        btnsEl[i].onclick = (function (i) {
          return function () {
            console.log(`当前索引${i}`);
          };
        })(i);
      }

      for (let i = 0; i < btnsEl.length; i++) {
        btnsEl[i].onclick = function () {
          console.log(`当前索引${i}`);
        };
      }*/

      // 添加自定义属性
      /*
        for (var i = 0; i < btnsEl.length; i++) {
          btnsEl[i].myIndex = i;
          btnsEl[i].onclick = function () {
            console.log(`当前索引${this.myIndex}`);
          };
        }
        
        btnsEl = null;
      */

      // 事件委托
      document.body.onclick = function (ev) {
        var target = ev.target;
        targetDom = target.tagName;
        if (targetDom === "BUTTON") {
          var index = target.getAttribute("index");
          console.log(`当前点击的是${index}`);
        }
      };
    </script>
  </body>
</html>
